import { useEffect, useState } from 'react'
import { FilePreviewState } from '../constants'
import './index.less'

function TextPreview({ configProps, setLoading, handleError, downloadFile }: FilePreviewState) {
  const [text, setText] = useState<string>('')
  const [cropped, setCropped] = useState<boolean>(false)
  useEffect(() => {
    // minio迁移到sso
    fetch(configProps.fileUrl)
      // fetch(`/api/v1/knowledge/download?file_path=${configProps.fileUrl}`)
      .then(response => {
        if (response.ok) {
          return response.text() || ''
        } else {
          throw new Error(`HTTP error! status: ${response.status}`)
        }
      })
      .then(text => {
        const len = text.length
        if (len > 10000) {
          text = text.substring(0, 10000)
          setCropped(true)
        }
        setText(text)
        setLoading(false)
      })
      .catch(error => {
        console.error('加载文本文件出错:', error)
        handleError(`${configProps.title}文件加载失败`)
      })
  }, [configProps])

  return (
    <div className="text-preview-styles min-h-[calc(100vh-200px)]">
      <pre className="text-styles">{text}</pre>
      {cropped && (
        <div className="text-preview-cropped">
          <div className="mb-[24px] mt-[8px]">......</div>
          预览时 TXT、LOG、JSON和Markdown文件默认只显示前1W个字符，可通过
          <span className="text-download-btn" onClick={() => downloadFile()}>
            下载
          </span>
          查看文件全部内容
        </div>
      )}
    </div>
  )
}

export default TextPreview
